<?php
namespace app\custom_user\controller;
use app\common\controller\ApiBaseController;
use app\custom_user\logic\UserLogic;
use app\custom_user\model\UserModel;
use app\custom_user\model\MobileCodeModel;

/**
 * 登录和注册的接口
 */
class PublicApiController extends ApiBaseController
{
    //注册用户
    public function register()
    {
        $ul=new UserLogic;
        $user=$ul->register($_REQUEST);
        if(!$user){
            $this->error($ul->getError());
        }
        $this->result($user,1);
    }
    //登录
    public function login()
    {
        $ul=new UserLogic;
        $user=$ul->login($_REQUEST);
        if(!$user){
            $this->error($ul->getError());
        }
        $this->result($user,1);
    }
    //查找用户
    public function getUserList()
    {
        $data=$_REQUEST;
        $um=new UserModel();

        $equal_fields=["username"];
        foreach($data as $key => $item){
            if(in_array($key,$equal_fields)){
                $um->where("$key = '$item'");
            }
        }

        $like_fields=["nickname","mobile"];
        foreach($data as $key => $item){
            if(in_array($key,$like_fields)){
                $um->where("$key like '%$item%'");
            }
        }

        $pagesize=isset($data["pagesize"])?$data["pagesize"]:20;
        $pagenum=isset($data["pagenum"])?$data["pagenum"]:1;
        $um->page($pagenum,$pagesize);

        $list=$um->field("id,username,nickname,mobile,create_time")->select();
        if(!$list){
            $this->error($um->getError());
        }
        $this->result($list,1);
    }
    //发送找回密码的手机验证码
    public function sendFindbackMobileCode()
    {
        $username=input("username");
        if(!$username){
            $this->error("用户账号不能为空");
        }
        $um=new UserModel;
        $user=$um->where(["username"=>$username])->find();
        if(!$user){
            $this->error("用户账号错误");
        }
        $mobile=$user["mobile"];
        $mcm=new MobileCodeModel;
        $result=$mcm->send($mobile,"findback");
        if(!$result){
            $this->error($mcm->getError());
        }
        $this->success("发送成功,手机号:$mobile");
    }
    //找回密码
    public function getbackPassword()
    {
        $ul=new UserLogic;
        $result=$ul->getbackPassword($_REQUEST);
        if(!$result){
            $this->error($ul->getError());
        }
        $this->success();
    }
}
